<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>欢迎注册</h2>
        <p>ZOMIOT 物联网平台</p>
      </div>
      
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        @finish="handleRegister"
        class="register-form"
      >
        <a-form-item name="username" has-feedback>
          <a-input
            v-model:value="formState.username"
            size="large"
            placeholder="请输入用户名（3-32个字符，仅限字母、数字和下划线）"
          >
            <template #prefix>
              <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="password" has-feedback>
          <a-input-password
            v-model:value="formState.password"
            size="large"
            placeholder="请输入密码（6-32个字符）"
          >
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="confirmPassword" has-feedback>
          <a-input-password
            v-model:value="formState.confirmPassword"
            size="large"
            placeholder="请确认密码"
          >
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="displayName">
          <a-input
            v-model:value="formState.displayName"
            size="large"
            placeholder="请输入昵称（可选，最多32个字符）"
          >
            <template #prefix>
              <SmileOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="telephone">
          <a-input
            v-model:value="formState.telephone"
            size="large"
            placeholder="请输入手机号（可选）"
          >
            <template #prefix>
              <MobileOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="email">
          <a-input
            v-model:value="formState.email"
            size="large"
            placeholder="请输入邮箱（可选）"
          >
            <template #prefix>
              <MailOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            size="large"
            :loading="loading"
            block
          >
            注册
          </a-button>
        </a-form-item>

        <div class="register-footer">
          已有账号？<a @click="goToLogin">立即登录</a>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { 
  UserOutlined, 
  LockOutlined, 
  SmileOutlined, 
  MobileOutlined, 
  MailOutlined 
} from '@ant-design/icons-vue'
import { registerApi } from '../api/auth.js'

const router = useRouter()
const formRef = ref()
const loading = ref(false)

// 表单数据
const formState = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  displayName: '',
  telephone: '',
  email: ''
})

// 自定义验证规则
const validateUsername = async (rule, value) => {
  if (!value) {
    return Promise.reject('用户名不能为空')
  }
  if (value.length < 3 || value.length > 32) {
    return Promise.reject('用户名长度必须在3-32字符之间')
  }
  if (!/^[a-zA-Z0-9_]+$/.test(value)) {
    return Promise.reject('用户名只能包含字母、数字和下划线')
  }
  return Promise.resolve()
}

const validatePassword = async (rule, value) => {
  if (!value) {
    return Promise.reject('密码不能为空')
  }
  if (value.length < 6 || value.length > 32) {
    return Promise.reject('密码长度必须在6-32字符之间')
  }
  return Promise.resolve()
}

const validateConfirmPassword = async (rule, value) => {
  if (!value) {
    return Promise.reject('请确认密码')
  }
  if (value !== formState.password) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

const validateDisplayName = async (rule, value) => {
  if (value && value.length > 32) {
    return Promise.reject('昵称长度不能超过32字符')
  }
  return Promise.resolve()
}

const validateTelephone = async (rule, value) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    return Promise.reject('手机号格式不正确')
  }
  return Promise.resolve()
}

const validateEmail = async (rule, value) => {
  if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
    return Promise.reject('邮箱格式不正确')
  }
  return Promise.resolve()
}

// 表单验证规则
const rules = {
  username: [
    { required: true, validator: validateUsername, trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  displayName: [
    { validator: validateDisplayName, trigger: 'blur' }
  ],
  telephone: [
    { validator: validateTelephone, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ]
}

// 处理注册
const handleRegister = async () => {
  try {
    loading.value = true
    
    // 准备注册数据
    const registerData = {
      username: formState.username,
      password: formState.password,
      displayName: formState.displayName || undefined,
      telephone: formState.telephone || undefined,
      email: formState.email || undefined
    }
    
    const response = await registerApi(registerData)
    
    // 根据实际后端返回的数据结构调整
    if (response.data.code === 200 || response.status === 200) {
      message.success('注册成功！请登录')
      
      // 延迟跳转到登录页面
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      message.error(response.data.message || '注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('注册失败:', error)
    message.error(error.response?.data?.message || '注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-box {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.register-header p {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.register-form {
  margin-top: 20px;
}

.register-footer {
  text-align: center;
  margin-top: 16px;
  color: #666;
}

.register-footer a {
  color: #667eea;
  font-weight: 500;
  cursor: pointer;
}

.register-footer a:hover {
  color: #764ba2;
}

:deep(.ant-input-affix-wrapper) {
  padding: 8px 11px;
}

:deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

:deep(.ant-btn-primary):hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

/* 响应式设计 */
@media (max-width: 576px) {
  .register-box {
    padding: 30px 20px;
  }
  
  .register-header h2 {
    font-size: 24px;
  }
}
</style>

